<template>
  <div class="buildings">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>楼栋管理</span>
          <div class="header-actions">
            <el-button @click="refreshBuildings" :loading="loading">
              刷新
            </el-button>
            <el-button type="primary" @click="openAddModal">
              新增楼栋
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索楼栋名称..."
          style="width: 300px; margin-right: 16px;"
          clearable
        >
        </el-input>
        <el-select v-model="statusFilter" placeholder="全部状态" style="width: 120px; margin-right: 16px;" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-select v-model="typeFilter" placeholder="全部类型" style="width: 120px;" clearable>
          <el-option label="男生宿舍" :value="0" />
          <el-option label="女生宿舍" :value="1" />
        </el-select>
      </div>

      <el-table :data="filteredBuildings" style="width: 100%" v-loading="loading">
        <el-table-column label="楼栋信息" min-width="200">
          <template #default="{ row }">
            <div class="building-info">
              <div class="building-name">{{ row.name }}</div>
              <div class="building-desc">ID: {{ row.id }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="楼层" width="80">
          <template #default="{ row }">
            {{ row.floorTotal }}层
          </template>
        </el-table-column>
        <el-table-column label="房间数" width="100">
          <template #default="{ row }">
            <div class="room-count">
              <span class="count">{{ row.roomTotal }}</span>
              <span class="label">间</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.tag)" size="small">
              {{ getTagText(row.tag) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="right">
          <template #default="{ row }">
            <el-button 
              type="warning" 
              size="small" 
              @click="editBuilding(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteBuilding(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑楼栋对话框 -->
    <el-dialog v-model="showModal" :title="modalTitle" width="600px">
      <el-form :model="buildingForm" label-width="80px">
        <el-form-item label="楼栋名称">
          <el-input 
            v-model="buildingForm.name"
            placeholder="请输入楼栋名称"
          />
        </el-form-item>
        <el-form-item label="楼层数">
          <el-input-number 
            v-model="buildingForm.floorTotal"
            :min="1"
            :max="20"
            placeholder="楼层数"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="房间数">
          <el-input-number 
            v-model="buildingForm.roomTotal"
            :min="1"
            placeholder="房间数"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="楼栋类型">
          <el-select v-model="buildingForm.type" placeholder="选择类型" style="width: 100%;">
            <el-option label="男生宿舍" :value="0" />
            <el-option label="女生宿舍" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="buildingForm.tag" placeholder="选择标签" style="width: 100%;">
            <el-option label="本科" :value="0" />
            <el-option label="研究生" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="buildingForm.status" placeholder="选择状态" style="width: 100%;">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="saveBuilding">
            {{ editingBuilding ? '保存' : '新增' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryDormBuild, addDormBuild, updateDormBuild, deleteDormBuild } from '@/apis/roomBuildAPI'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const showModal = ref(false)
const editingBuilding = ref(null)

// 楼栋表单
const buildingForm = ref({
  name: '',
  floorTotal: 0,
  roomTotal: 0,
  type: 0,
  tag: 0,
  status: 1
})

// 楼栋数据
const buildings = ref([])

// 计算属性
const filteredBuildings = computed(() => {
  let filtered = buildings.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(building => 
      building.name.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value !== '' && statusFilter.value !== null && statusFilter.value !== undefined) {
    filtered = filtered.filter(building => building.status === statusFilter.value)
  }

  // 类型过滤
  if (typeFilter.value !== '' && typeFilter.value !== null && typeFilter.value !== undefined) {
    filtered = filtered.filter(building => building.type === typeFilter.value)
  }

  return filtered
})

const modalTitle = computed(() => editingBuilding.value ? '编辑楼栋' : '新增楼栋')

// 方法
const getTypeText = (type) => {
  const typeMap = {
    0: '男生宿舍',
    1: '女生宿舍',
  }
  return typeMap[type] || '未知类型'
}

const getTypeTagType = (type) => {
  const typeMap = {
    0: 'primary',
    1: 'danger'
  }
  return typeMap[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '正常',
    0: '停用'
  }
  return statusMap[status] || '未知状态'
}

const getStatusTagType = (status) => {
  const typeMap = {
    1: 'success',
    0: 'info'
  }
  return typeMap[status] || 'info'
}

const getTagText = (tag) => {
  const tagMap = {
    0: '本科',
    1: '研究生'
  }
  return tagMap[tag] || '未知标签'
}

const getTagType = (tag) => {
  const typeMap = {
    0: 'success',
    1: 'warning'
  }
  return typeMap[tag] || 'info'
}

const refreshBuildings = async () => {
  loading.value = true
  try {
    const response = await queryDormBuild()
    if (response.code === 0) {
      buildings.value = response.data
      ElMessage.success('数据刷新成功')
    } else {
      ElMessage.error(response.msg || '加载数据失败')
    }
  } catch (error) {
    console.error('加载楼栋数据失败:', error)
    ElMessage.error('刷新失败，请重试')
  } finally {
    loading.value = false
  }
}

const openAddModal = () => {
  editingBuilding.value = null
  buildingForm.value = {
    name: '',
    floorTotal: 0,
    roomTotal: 0,
    type: 0,
    tag: 0,
    status: 1
  }
  showModal.value = true
}

const editBuilding = (building) => {
  editingBuilding.value = building
  // 把后端字段映射到表单字段
  buildingForm.value = {
    name: building.name || '',
    floorTotal: building.floorTotal ?? 1,
    roomTotal: building.roomTotal ?? 1,
    type: building.type ?? 0,
    tag: building.tag ?? 0,
    status: building.status ?? 1
  }
  showModal.value = true
}

const deleteBuilding = async (building) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除楼栋 "${building.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    loading.value = true
    try {
      const res = await deleteDormBuild(building.id)
      if (res && res.code === 0) {
        ElMessage.success('楼栋删除成功')
        await refreshBuildings()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (err) {
      console.error('删除楼栋失败:', err)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  } catch {
    // 用户取消操作
  }
}

const saveBuilding = async () => {
  // 构建与后端一致的 payload
  const payload = {
    name: buildingForm.value.name,
    floorTotal: Number(buildingForm.value.floorTotal),
    roomTotal: Number(buildingForm.value.roomTotal),
    type: Number(buildingForm.value.type),
    tag: Number(buildingForm.value.tag),
    status: Number(buildingForm.value.status)
  }

  loading.value = true
  try {
    if (!editingBuilding.value) {
      // 新增
      const res = await addDormBuild(payload)
      if (res && res.code === 0) {
        ElMessage.success('楼栋添加成功')
        await refreshBuildings()
        closeModal()
      } else {
        ElMessage.error(res.msg || '新增失败')
      }
    } else {
      // 编辑
      if (!editingBuilding.value || !editingBuilding.value.id) {
        ElMessage.error('未选择要编辑的楼栋')
        return
      }
      // 把 id 加到 payload
      payload.id = editingBuilding.value.id
      const res = await updateDormBuild(payload)
      if (res && res.code === 0) {
        ElMessage.success('楼栋信息更新成功')
        await refreshBuildings()
        closeModal()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    }
  } catch (err) {
    console.error('保存楼栋失败:', err)
    ElMessage.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

const closeModal = () => {
  showModal.value = false
  editingBuilding.value = null
  buildingForm.value = {
    name: '',
    floorTotal: 6,
    roomTotal: 120,
    type: 0,
    tag: 0,
    status: 1
  }
}

onMounted(() => {
  refreshBuildings()
})
</script>

<style scoped>
.buildings {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.building-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.building-name {
  font-weight: 500;
  color: #303133;
}

.building-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.code-badge {
  background: #f5f7fa;
  color: #303133;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  font-family: monospace;
}

.room-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.count {
  font-weight: 600;
  color: #303133;
}

.label {
  color: #909399;
  font-size: 12px;
}


.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .buildings {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: stretch;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section .el-input,
  .search-section .el-select {
    width: 100% !important;
  }
}
</style>